//
//  CAddressListView.m
//  HCHK_iphone
//
//  Created by yilong zhang on 12-1-12.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "CAddressListView.h"

//========================================================================================================================

@implementation CResInfo

@synthesize m_strName;
@synthesize m_strVici;
@synthesize m_fLat;
@synthesize m_fLon;
@synthesize m_nType;

-(id)initWithDic:(NSDictionary*)dic
{
    self = [super init];
    if (self)
    {
        NSDictionary *location = [dic objectForKey:@"geometry"];
        location = [location objectForKey:@"location"];
        
        self.m_fLat = [[location objectForKey:@"lat"] floatValue];
        self.m_fLon = [[location objectForKey:@"lng"] floatValue];
        
        self.m_strName = [dic objectForKey:@"name"];
        self.m_strVici = [dic objectForKey:@"vicinity"];
    }
    
    return self;
}

-(id)initWithName:(NSString*)name
{
    self = [super init];
    if (self)
    {
        self.m_strName = name;
        self.m_strVici = name;
        
        self.m_fLat = 0.000000;
        self.m_fLon = 0.000000;
    }
    
    return self;
}

-(void)dealloc
{
    [m_strName release];
    [m_strVici release];
    
    [super dealloc];
}

@end

//========================================================================================================================

@implementation CAddr

@synthesize m_X;
@synthesize m_Y;
@synthesize m_City;
@synthesize m_Province;
@synthesize m_Country;
@synthesize m_Detail;

-(id)init
{
    self = [super init];
    if (self)
    {
        m_Detail = [[NSString alloc] initWithString:@"陕西省西安市"];
        m_City   = [[NSString alloc] initWithString:@"西安"];
        m_X      = [[NSString alloc] initWithString:@"0.000000"];
        m_Y      = [[NSString alloc] initWithString:@"0.000000"];
        m_Country= [[NSString alloc] initWithString:@"中国"];
        m_Province=[[NSString alloc] initWithString:@"陕西省"];
    }
    
    return self;
}

-(void)dealloc
{
    [m_X release];
    [m_Y release];
    [m_City release];
    [m_Detail release];
    [m_Country release];
    [m_Province release];
    
    [super dealloc];
}

@end

//========================================================================================================================

@implementation CAddressListView

@synthesize delegate;
@synthesize m_Bar;
@synthesize m_Seg;
@synthesize m_List;
@synthesize m_Addr;
@synthesize m_Contents;
@synthesize m_ShowStyle;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        UIImageView *bg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
        bg.image = [UIImage imageNamed:@"appbg.jpg"];
        [self addSubview:bg];
        [bg release];
        
        m_Contents = [[NSMutableArray array] retain];
        m_Addr = [[CAddr alloc] init];
        m_ShowStyle = 0;
        
        CResInfo *temp = [[CResInfo alloc] init];
        temp.m_strName = @"手动添加美食信息";
        temp.m_strVici = @" ";
        [m_Contents addObject:temp];
        [temp release];
        
        //m_Bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 51)]; 
        //m_Bar.backgroundColor = [UIColor clearColor];
        UIImageView *view = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 51)];
        view.image = [UIImage imageNamed: @"barbg.png"];
        [self addSubview:view];
        //[m_Bar addSubview:view];
        [view release];
        //[self addSubview:m_Bar];
        //[m_Bar release];
        
        //UINavigationItem *item = [[UINavigationItem alloc] init];
        //[m_Bar pushNavigationItem:item animated:NO];
        //[item release];
        
        UIImageView *m_TopLog = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"renname.png"]];
        m_TopLog.frame = CGRectMake(0, 12, 80, 22);
        m_TopLog.center= CGPointMake(self.frame.size.width/2, view.frame.size.height/2-2);
        [self addSubview:m_TopLog];
        [m_TopLog release];
        
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(self.frame.size.width-55, 3, 45, 45);
        //btn.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn setBackgroundImage:[UIImage imageNamed:@"local.png"] forState:UIControlStateNormal];
        //[btn setTitle:@"我的附近" forState:UIControlStateNormal];
        //[btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(UpDateAddrList) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        //item.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:btn] autorelease];
        
        /*btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(0, 0, 60, 32);
        btn.titleLabel.font = [UIFont systemFontOfSize:13];
        [btn setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
        [btn setTitle:@"保存" forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(CancelSelected) forControlEvents:UIControlEventTouchUpInside];
        item.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:btn] autorelease];*/
        
        m_List = [[UITableView alloc] initWithFrame:CGRectMake(0, 45, frame.size.width, frame.size.height-50)];
        m_List.backgroundColor = [UIColor clearColor];
        m_List.separatorStyle = UITableViewCellSeparatorStyleNone;
        m_List.delegate = self;
        m_List.dataSource= self;
        [self addSubview:m_List];
        [m_List release];
    }
    return self;
}

-(void)dealloc
{
    [m_Contents release];
    
    [super dealloc];
}

-(void)LoadPositions
{
    [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"位置获取中..."];
    
    if (1 == [m_Contents count])
    {
        [self GetCurPosition];
    }
    else 
    {
        [m_List reloadData];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
}

-(void)GetCurPosition
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdatePosition:) name:MSG_LOCATION_RET object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(UpdatePosition:) name:MSG_LOCATION_TIMEOUT object:nil];

    [m_Contents removeAllObjects];
    CResInfo *temp = [[CResInfo alloc] init];
    temp.m_strName = @"手动添加美食信息";
    temp.m_strVici = @" ";
    [m_Contents addObject:temp];
    [temp release];
    [m_List reloadData];
    
    //地位信息
    if (NormalSupport != [[CLocator DefaultLocator] StartLocation])
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_TIMEOUT object:nil];
        
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        
        UIAlertView *nolocal = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位功能未打开，不能使用。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [nolocal show];
        [nolocal autorelease];
    }
    else 
    {
        //保存定位信息-hchk-test-start
        /*CAddrInfo *info = [CLocator DefaultLocator].m_AddrInfo;
        self.m_Addr.m_Detail   = [[[NSString alloc] initWithString:info.m_strSum] autorelease];
        self.m_Addr.m_City     = [[[NSString alloc] initWithFormat:@"%@", info.m_strCity] autorelease];
        self.m_Addr.m_Province = [[[NSString alloc] initWithFormat:@"%@", info.m_strProvince] autorelease];
        self.m_Addr.m_Country  = [[[NSString alloc] initWithFormat:@"%@", info.m_strCountry] autorelease];
        self.m_Addr.m_X        = [[[NSString alloc] initWithFormat:@"%f", info.m_fX] autorelease];
        self.m_Addr.m_Y        = [[[NSString alloc] initWithFormat:@"%f", info.m_fY] autorelease];*/
        //hchk-test-end
    }
}

-(void)UpDateAddrList
{
    [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"位置获取中..."];
    [self GetCurPosition];
}

-(void)CancelSelected
{
    [delegate DidAddressListViewActived:self Command:0 Value1:[NSNumber numberWithInt:-1] Value2:nil];
}

-(void)GetPointRoundInfo:(CLLocationCoordinate2D)coordinate
{
    CNetWorkRequest *request = [[CNetWorkRequest alloc] init];
    request.m_Delegate = self;
    
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/search/json?location=%f,%f&radius=100&types=food&sensor=false&key=AIzaSyCl0XF2PHczXCQHZN3c94Rf3DWdqrWrBpA", coordinate.latitude, coordinate.longitude];
    [request SetRequestWithUrl:url Method:Get Value:nil IsSynchronous:NO OutTime:10];
}

-(void)DidReceiveData:(CNetWorkRequest *)request Data:(NSMutableData *)data
{
    [m_Contents removeAllObjects];
    CResInfo *temp = [[CResInfo alloc] init];
    temp.m_strName = @"手动添加美食信息";
    temp.m_strVici = @" ";
    [m_Contents addObject:temp];
    [temp release];
    
    NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [json JSONValue];
    
    if (dic)
    {
        NSArray *items = [dic objectForKey:@"results"];
        if (items && [items count] > 0)
        {
            CResInfo *resinfo = nil;
            for (NSDictionary *info in items)
            {
                resinfo = [[CResInfo alloc] initWithDic:info];
                resinfo.m_nType = 1;
                [m_Contents addObject:resinfo];
                [resinfo release];
                
                if ([m_Contents count] > 30)
                {
                    break;
                }
            }
            
            [m_List reloadData];
        }
        else 
        {
            UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时无法获得信息，稍后再试或手动输入。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [error show];
            [error autorelease];
        }
    }
    
    [json release];
    [request release];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)SaveResInfo
{
    NSArray *infos = [NSArray arrayWithArray:m_Contents];
    NSString *path = [NSString stringWithFormat:@"%@/Documents/resinfo.dat", NSHomeDirectory()];
    [infos writeToFile:path atomically:YES];
}

-(void)GetResInfo
{
    //
}

-(void)DidRectiveTimeout:(CNetWorkRequest *)request
{
    UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时无法获得信息，稍后再试或手动输入。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [error show];
    [error autorelease];
    
    [request release];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DidReceiveError:(CNetWorkRequest *)request Error:(NSError *)error
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时无法获得信息，稍后再试或手动输入。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [alter show];
    [alter autorelease];
    
    [request release];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)DidStopRequestNoNet:(CNetWorkRequest *)request
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时无法获得信息，稍后再试或手动输入。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [alter show];
    [alter autorelease];
    
    [request release];
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

-(void)UpdatePosition:(NSNotification*)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_TIMEOUT object:nil];
    
    CAddrInfo *info = notification.object;
    
    if (info)
    {
        //还原定位信息-hchk-test-start
        /*CAddrInfo *infos = [CLocator DefaultLocator].m_AddrInfo;
        infos.m_fX = [self.m_Addr.m_X floatValue];
        infos.m_fY = [self.m_Addr.m_Y floatValue];
        infos.m_strCity     = [[[NSString alloc] initWithFormat:@"%@", self.m_Addr.m_City] autorelease];
        infos.m_strProvince = [[[NSString alloc] initWithFormat:@"%@", self.m_Addr.m_Province] autorelease];
        infos.m_strCountry  = [[[NSString alloc] initWithFormat:@"%@", self.m_Addr.m_Country] autorelease];
        infos.m_strSum      = [[NSString alloc] initWithFormat:@"%@", self.m_Addr.m_Detail];
        [CLocator DefaultLocator].m_Coordinate2D = [CLocator DefaultLocator].m_Coordinate2D = CLLocationCoordinate2DMake(infos.m_fX, infos.m_fY);*/
        //hchk-test-end
        
        //设置定位得到的信息
        self.m_Addr.m_Detail   = [[[NSString alloc] initWithString:info.m_strSum] autorelease];
        self.m_Addr.m_City     = [[[NSString alloc] initWithFormat:@"%@", info.m_strCity] autorelease];
        self.m_Addr.m_Province = [[[NSString alloc] initWithFormat:@"%@", info.m_strProvince] autorelease];
        self.m_Addr.m_Country  = [[[NSString alloc] initWithFormat:@"%@", info.m_strCountry] autorelease];
        self.m_Addr.m_X        = [[[NSString alloc] initWithFormat:@"%f", info.m_fX] autorelease];
        self.m_Addr.m_Y        = [[[NSString alloc] initWithFormat:@"%f", info.m_fY] autorelease];
        
        [self GetPointRoundInfo:CLLocationCoordinate2DMake(/*34.284, 108.947*/info.m_fX, info.m_fY)];
    }
    else
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        
        UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂时无法获得信息，稍后再试或手动输入。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [error show];
        [error autorelease];
    }
    
    [m_Seg setEnabled:YES forSegmentAtIndex:1];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [m_Contents count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float fHeight = 70;
    if (0 == indexPath.row)
        fHeight = 40;
    
    return fHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCellStyle style = UITableViewCellStyleSubtitle;
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BaseCell"];
	
	if (nil == cell)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:style reuseIdentifier:@"BaseCell"] autorelease];
        cell.backgroundView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 70)] autorelease];
        
        cell.textLabel.numberOfLines = 2;
        cell.textLabel.font = [UIFont fontWithName:@"Helvetica" size:14];
        
        cell.detailTextLabel.numberOfLines = 2;
        cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica" size:13];
        cell.textLabel.numberOfLines = 2;
    }
    
    CResInfo *info = [m_Contents objectAtIndex:indexPath.row];
    if (0 == m_ShowStyle)
    {
        cell.textLabel.text = info.m_strName;
        cell.detailTextLabel.text = nil;
    }
    else if (2 == m_ShowStyle)
    {
        cell.textLabel.text = info.m_strName;
        cell.detailTextLabel.text = info.m_strVici;
    }
    else if (3 == m_ShowStyle)
    {
        cell.textLabel.text = info.m_strVici;
        cell.detailTextLabel.text = info.m_strName;
    }
    else 
    {
        cell.textLabel.text = info.m_strVici;
        cell.detailTextLabel.text = nil;
    }
    
    if (0 == indexPath.row%2)
    {
        if (0 == indexPath.row)
        {
            cell.backgroundView.backgroundColor = [UIColor greenColor];
        }
        else 
        {
            cell.backgroundView.backgroundColor = [UIColor whiteColor];
        }
    }
    else 
    {
        cell.backgroundView.backgroundColor = self.backgroundColor;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [delegate DidAddressListViewActived:self Command:0 Value1:[NSNumber numberWithInt:indexPath.row] Value2:[m_Contents objectAtIndex:indexPath.row]];
}

@end
